﻿using Core.Dtos;
using Core.Entities;
using Core.IRepository;
using Core.Messages;
using Core.Queries;
using Library.Helpers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace Front.Controllers.Api
{
    public class ReadBaseController<TId, TEntity, TDto, TQuery> : ApiController
        where TDto : BaseDto<TId>
        where TEntity : BaseEntity<TId>
        where TQuery : BaseQuery<TEntity>
    {
        protected IUnitOfWork UnitOfWork;
        protected IBaseRepository<TId, TEntity> Repository;

        public ReadBaseController(IUnitOfWork unitOfWork, IBaseRepository<TId, TEntity> Repository)           
        {
            this.UnitOfWork = unitOfWork;
            this.Repository = Repository;
        }
    
        // GET api/<controller>/5
        public virtual TDto Get(TId id)
        {
            TEntity entity = Repository.FindBy(id);
            TDto dto = default(TDto);
            if(entity != null)
                dto = AutoMapper.Mapper.Map<TEntity, TDto>(entity);
            return dto;
        }

        protected ListResponse<TDto> DefaultFindBy(TQuery query)
        {
            return DefaultFindBy<TDto>(query);
        }

        protected ListResponse<TVM> DefaultFindBy<TVM>(TQuery query)
        {
            query = query ?? (TQuery)Activator.CreateInstance(typeof(TQuery));
            ListResponse<TVM> response = new ListResponse<TVM>();
            try
            {
                ListResponse<TEntity> dbResponse = Repository.FindBy(query);

                response.List = AutoMapperHelper.MapList<TEntity, TVM>(dbResponse.List).ToList();
                response.RowsCount = dbResponse.RowsCount;
                response.PageNumber = query.PageNumber;
                response.PageSize = query.PageSize;
                response.Success = true;
            }
            catch (Exception ex)
            {
                response.Success = false;
                response.ErrorMessage = ex.ToString();
            }

            return response;           
        }
    }
}
